#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2019/4/9  21:03
# @Author: 余浪人
# @email: yulangren520@gmail.com
from flask_login import login_user, login_required, logout_user
from apps import get_sys_uri
from apps.cms import cms_bp
from flask import render_template, request, jsonify, redirect, url_for, current_app
from apps.forms.admin_form import Login_Form
from apps.forms.system_form import System_Form, Ad_Form, Blogroll_Form, Share_Form, Discuss_Form, Api_Form, \
    Accredit_Form
from apps.lib.pwd_verify import check_password
from apps.models.admin_model import Admin_Model
from apps.models.collector_model import Collector_Model
from apps.models.column_model import Column_model
from apps.models.document_model import Document_Model
from apps.models.member_model import Member
from apps.models.system_model import System_Model, db, Ad_Model, Blogroll_Model, Share_Modle, Discuss_Model, Log_Model, API_Modle, Accredit_Model
from apps.lib.public import edit_data, check_obj, add_data, real_delete_data, real_deletes, errors, log, \
    page_auto, api_edit


# 系统主框架
@cms_bp.route('/sys_frame', endpoint='sys_frame', methods=['GET'])
@login_required
def sys_frame():
    return render_template('sys_templates/base_frame.html')


# 系统头部
@cms_bp.route('/sys_top_frame', endpoint='sys_top_frame', methods=['GET'])
@login_required
def sys_top_frame():
    return render_template('sys_templates/top_frame.html')


# 系统菜单
@cms_bp.route('/sys_left_frame', endpoint='sys_left_frame', methods=['GET'])
@login_required
def sys_top_frame():
    return render_template('sys_templates/left_frame.html')


# 系统首页
@cms_bp.route('/sys_index', endpoint='sys_index', methods=['GET'])
@login_required
def index():
    log('成功登录管理中心!')
    host = current_app.config.get('HOST')  # 域名
    port = current_app.config.get('PORT')  # 端口
    col_num = Column_model.query.filter().count()  # 栏目数
    doc_num = Document_Model.query.filter().count()  # 档案数
    coll_num = Collector_Model.query.filter().count()  # 采集规则数
    member_num = Member.query.filter().count()  # 会员数
    admin_num = Admin_Model.query.filter().count()  # 管理员数
    data_s = {"host": host, 'port': port, 'col_num': col_num, "doc_num": doc_num, 'coll_num': coll_num,
              'member_num': member_num, 'admin_num': admin_num, 'sys_path': get_sys_uri()}
    return render_template('sys_templates/index.html', data_s=data_s)


# 系统登录
@cms_bp.route('/admin', endpoint='login', methods=['GET', 'POST'])
def login():
    form = Login_Form(request.form)
    if request.method == 'POST':
        username = request.form.get('username').strip()
        password = request.form.get('password')
        if form.validate() and username and password:
            obj = Admin_Model.query.filter_by(username=username).first()
            if not check_obj(obj) and obj:  # 验证密码
                if check_password(obj.password, password):
                    login_user(obj)
                    return jsonify({"status": 0, "message": "登录成功!"})
                return jsonify({"status": 1, "message": "用户密码错误!"})
        return jsonify({"status": 1, "message": errors(form)})
    else:
        return render_template('sys_templates/login.html', title='管理员登录')


# 系统退出
@cms_bp.route('/logout', endpoint='logout', methods=['GET'])
@login_required
def logout():
    log('退出系统!')
    logout_user()
    return redirect(url_for('cms_bp.login'))


# 系统设置
@cms_bp.route('/sys_set', endpoint='system_ser', methods=['GET', 'POST'])
@login_required
def system_ser():
    log('操作系统设置')
    obj = System_Model.query.filter().first()
    if request.method == 'POST':
        return edit_data(System_Form, System_Model, db, obj.id)
    elif not check_obj(obj):
        form = System_Form(data=dict(obj))
        return render_template('sys_templates/system_set.html', form=form, title='系统设置')


# 广告管理-列表
@cms_bp.route('/ad_list', endpoint='ad_list', methods=['GET', 'DELETE', 'DELETE_S'])
@login_required
def AD_list():
    log('操作广告管理列表')
    if request.method == 'DELETE':
        try:
            uid = int(request.form.get('uid'))
            if uid <= 5: return jsonify({"status": 1, "message": "不可删除系统广告位!"})
            obj = Ad_Model.query.filter_by(id=uid).first()
            if not check_obj(obj) and obj:
                db.session.delete(obj)
            else:
                return jsonify({"status": 1})
        except:
            db.session.rollback()
            return jsonify({"status": 1, "message": "数据库操作异常!"})
        db.session.commit()
        return jsonify({"status": 0})
    elif request.method == 'DELETE_S':
        uid_s = list(eval(request.form.get('data_s') + ','))
        try:
            for uid in uid_s:
                if int(uid) <= 5: return jsonify({"status": 1, "message": "含系统广告位,不可删除!"})
                obj = Ad_Model.query.filter_by(id=uid).first()
                if not check_obj(obj) and uid: db.session.delete(obj)
        except:
            db.session.rollback()
            return jsonify({"status": 1, "message": "数据库操作异常!"})
        db.session.commit()
        return jsonify({"status": 0})
    data_s = Ad_Model.query.order_by(db.desc(Ad_Model.id))
    paginate, page = page_auto(data_s)
    return render_template('sys_templates/ad_list.html', data_s=paginate, page=page, title='广告列表管理',
                           url='cms_bp.ad_list')


# 广告管理-添加
@cms_bp.route('/ad_add', endpoint='ad_add', methods=['GET', 'POST'])
@login_required
def AD_add():
    log('操作广告添加')
    if request.method == 'POST':
        return add_data(Ad_Model, Ad_Form, db)
    form = Ad_Form(request.form)
    return render_template('sys_templates/ad.html', form=form, title='新建广告位')


# 广告管理-修改
@cms_bp.route('/ad_edit/<int:id>', endpoint='ad_edit', methods=['GET', 'POST'])
@login_required
def AD_add(id):
    if request.method == 'POST':
        log('操作广告修改')
        return edit_data(Ad_Form, Ad_Model, db, id)
    obj = Ad_Model.query.filter_by(id=id).first()
    if not check_obj(obj):
        form = Ad_Form(data=dict(obj))
        return render_template('sys_templates/ad.html', form=form, title=f'修改:{obj.ad_name}')


# 友情链接-列表
@cms_bp.route('/blogroll_list', endpoint='blogroll_list', methods=['GET', 'DELETE', 'DELETE_S'])
@login_required
def blogroll_list():
    if request.method == 'DELETE':
        log('操作删除友情链接')
        return real_delete_data(Blogroll_Model, db, request.form.get('uid'))
    elif request.method == 'DELETE_S':
        log('操作批量删除友情链接')
        return real_deletes(Blogroll_Model, db, uid_s=list(eval(request.form.get('data_s') + ',')))
    data_s = Blogroll_Model.query.order_by(db.desc(Blogroll_Model.id))
    log('操作友情链接')
    paginate, page = page_auto(data_s)
    return render_template('sys_templates/blogroll_list.html', data_s=paginate, page=page, url='cms_bp.blogroll_list',
                           title='友情链接列表')


# 友情链接-添加
@cms_bp.route('/blogroll_add', endpoint='blogroll_add', methods=['GET', 'POST'])
@login_required
def blogroll_add():
    if request.method == 'POST':
        log('操作友情链接添加')
        return add_data(Blogroll_Model, Blogroll_Form, db)
    form = Blogroll_Form(request.form)
    return render_template('sys_templates/blogroll.html', form=form, title='添加链接')


# 友情链接-修改
@cms_bp.route('/blogroll_edit/<int:id>', endpoint='blogroll_edit', methods=['GET', 'POST'])
@login_required
def blogroll_add(id):
    if request.method == 'POST':
        log('操作友情修改')
        return edit_data(Blogroll_Form, Blogroll_Model, db, id)
    obj = Blogroll_Model.query.filter_by(id=id).first()
    if not check_obj(obj):
        form = Blogroll_Form(data=dict(obj))
        return render_template('sys_templates/blogroll.html', form=form, title=f'修改:{obj.link_name}')


# 分享功能
@cms_bp.route('/share', endpoint='share', methods=['GET', 'POST'])
@login_required
def share():
    obj = Share_Modle.query.filter().first()
    if request.method == 'POST':
        return edit_data(Share_Form, Share_Modle, db, obj.id)
    elif not check_obj(obj):
        form = Share_Form(data=dict(obj))
        return render_template('sys_templates/share_set.html', form=form, title='分享接口设置')


# 评论功能
@cms_bp.route('/discuss', endpoint='discuss', methods=['GET', 'POST'])
@login_required
def share():
    obj = Discuss_Model.query.filter().first()
    if request.method == 'POST':
        return edit_data(Discuss_Form, Discuss_Model, db, obj.id)
    elif not check_obj(obj):
        form = Discuss_Form(data=dict(obj))
        return render_template('sys_templates/discuss_set.html', form=form, title='评论接口设置')


# API功能
@cms_bp.route('/api_set', endpoint='api_set', methods=['GET', 'POST'])
@login_required
def share():
    obj = API_Modle.query.filter().first()
    if request.method == 'POST':
        return api_edit(Api_Form, API_Modle, db, obj.id)
    elif not check_obj(obj):
        form = Api_Form(data=dict(obj))
        return render_template('sys_templates/api_set.html', form=form, title='API接口设置')


@cms_bp.route('/accredit_set', endpoint='accredit_set', methods=['GET', 'POST'])
@login_required
def accredit_set():
    accredit_obj = Accredit_Model.query.filter().first()
    if request.method == 'POST':
        return #TODO 验证授权 远程服务器
    form = Accredit_Form(data=dict(accredit_obj))
    return render_template('sys_templates/accredit_set.html', form=form, title='系统授权')


# 后台日志模块
@cms_bp.route('/log_list', endpoint='log_list', methods=['GET', 'DELETE', 'DELETE_S'])
@login_required
def log_list():
    if request.method == 'DELETE':
        return real_delete_data(Log_Model, db, request.form.get('uid'))
    elif request.method == 'DELETE_S':
        return real_deletes(Log_Model, db, uid_s=list(eval(request.form.get('data_s') + ',')))
    data_s = Log_Model.query.order_by(db.desc(Log_Model.id))
    paginate, page = page_auto(data_s)
    return render_template('sys_templates/log_list.html', data_s=paginate, page=page, url='cms_bp.log_list',
                           title='日志管理列表')
